package com.pnk087.servlet.chapter05;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: khanhpham
 * Date: 5/4/12
 * Time: 5:44 AM
 * To change this template use File | Settings | File Templates.
 */
public class ServletB extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        /*
        This is to show the idea that we cannot guarantee that "foo" will not be changed between SET and GET even in a synchronized block like this.
        To prove that, access ServletB and and access ServletA right after that (before 5secs) and you will see "100" is printed out instead of "101".
        This is because in ServletA we don't put getServletContext().setAttribute() in synchronized block.
         */
        synchronized (getServletContext()) {
            getServletContext().setAttribute("foo", "101");
            System.out.println();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            System.out.println(getServletContext().getAttribute("foo"));
        }
    }
}
